class_name UnitSnake
extends UnitBase

@onready var edge_ray_tester: RayCast2D = $ViewRoot/EdgeRayTester

var target_velocity: Vector2 = Vector2.ZERO


func pick_new_wander_target():
	if target_velocity.x == 0:
		target_velocity.x = speed if randf() < 0.5 else -speed
	else:
		target_velocity.x = speed if target_velocity.x < 0 else -speed
	
	velocity = target_velocity
	if velocity.x:
		set_face(sign(velocity.x))
	
	# 下一次切换目标时间
	timer = randf_range(2.0, change_dir_time)


func play_wander_animation():
	animation_player.play("walk")


func process_approach(delta: float):
	if not attack_target: 
		states.transition("Wander")
		return
	
	var target_pos = attack_target.global_position
	var dir = sign(target_pos.x - global_position.x) 
	var dx = target_pos.x - global_position.x
	
	if abs(dx) > 5:
		velocity.x = dir * speed
		animation_player.play("walk")
	else:
		velocity.x = 0
		animation_player.play("idle")
	
	if not edge_ray_tester.is_colliding():
		velocity.x = 0
		animation_player.play("idle")
	
	move_and_slide()
	

func process_wander(delta: float):
	timer -= delta
	if timer <= 0.0 or not edge_ray_tester.is_colliding():
		pick_new_wander_target()

	velocity.x = lerp(velocity.x, target_velocity.x, 0.05) 
	move_and_slide()
	
	
	
